#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/types.h>

typedef struct {
    char name[4];
    int age;
} student;

int main(int argc, char** argv) {
    int fd;
    student *p_map;
    char temp;

    // 打开文件并检查错误
    fd = open("stu.txt", O_CREAT | O_RDWR | O_TRUNC, 0777);
    if (fd == -1) {
        perror("open");
        exit(1);
    }

    // 调整文件大小
    if (lseek(fd, sizeof(student) * 10 - 1, SEEK_SET) == -1) {
        perror("lseek");
        close(fd);
        exit(1);
    }
    if (write(fd, "", 1) == -1) {
        perror("write");
        close(fd);
        exit(1);
    }

    // mmap 映射并检查错误
    p_map = (student*)mmap(NULL, sizeof(student) * 10, 
                          PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (p_map == (void*)-1) {
        perror("mmap failed");
        close(fd);
        exit(1);
    }
    close(fd); // 映射后可关闭文件描述符

    temp = 'a';
    for (int i = 0; i < 10; i++) {
        // 处理姓名，确保不越界
        if (i < 26) { // 简单限制，避免temp超出字符范围
            memcpy((p_map + i)->name, &temp, 2);
            (p_map + i)->name[2] = '\0'; // 明确添加结束符
            temp += 1;
        }
        (p_map + i)->age = 20 + i;
    }

    sleep(10);
    munmap(p_map, sizeof(student) * 10);
    return 0;
}
